#include <49func.h>
int main(int argc, char *argv[])
{
    // ./4_server 192.168.118.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);//udp SOCK_DGRAM
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(atoi(argv[2]));
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = bind(sockfd,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
    ERROR_CHECK(ret,-1,"bind");
    // 服务端先recvfrom
    struct sockaddr_in clientAddr;
    socklen_t clientAddrSize = sizeof(clientAddr);
    char buf[4096] = {0};
    recvfrom(sockfd,buf,sizeof(buf),0,
            (struct sockaddr *)&clientAddr,&clientAddrSize);
    printf("client ip = %s, port = %d\n",
           inet_ntoa(clientAddr.sin_addr),ntohs(clientAddr.sin_port));
    printf("buf = %s\n", buf);
    fd_set rdset;
    while(1){
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO,&rdset);
        FD_SET(sockfd,&rdset);
        select(sockfd+1,&rdset,NULL,NULL,NULL);
        if(FD_ISSET(STDIN_FILENO,&rdset)){
            bzero(buf,sizeof(buf));
            ssize_t sret = read(STDIN_FILENO,buf,sizeof(buf));
            if(sret == 0){
                sendto(sockfd,buf,0,0,
                       (struct sockaddr *)&clientAddr,
                       clientAddrSize);
                break;
            }
            sendto(sockfd,buf,strlen(buf),0,
                   (struct sockaddr *)&clientAddr,
                   clientAddrSize);
        }
        if(FD_ISSET(sockfd,&rdset)){
            bzero(buf,sizeof(buf));
            ssize_t sret = recvfrom(sockfd,buf,sizeof(buf),0,NULL,NULL);
            if(sret == 0){
                break;
            }
            printf("buf = %s\n", buf);
        }
    }
    close(sockfd);
    return 0;
}

